/*
 * Copyright 2011 Google Inc. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package ru.vpitervip.app.client.activity;

import java.util.ArrayList;
import java.util.List;
import java.util.logging.Logger;


import ru.vpitervip.app.client.place.FlatsPlace;
import ru.vpitervip.app.client.request.AppApplicationRequest;
import ru.vpitervip.app.client.request.AppFlatRequest;
import ru.vpitervip.app.client.request.AppRequestFactory;
import ru.vpitervip.app.client.ui.FlatsView;
import ru.vpitervip.app.client.ui.FlatView;
import ru.vpitervip.app.client.ui.BookingView;
import ru.vpitervip.app.client.ui.FlatsViewImpl;
import ru.vpitervip.client.managed.request.ApplicationProxy;
import ru.vpitervip.client.managed.request.FacilityProxy;
import ru.vpitervip.client.managed.request.FlatProxy;
import ru.vpitervip.client.managed.request.MetroStationProxy;

import com.google.gwt.activity.shared.AbstractActivity;
import com.google.gwt.event.shared.EventBus;
import com.google.gwt.place.shared.Place;
import com.google.gwt.place.shared.PlaceController;

import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.AcceptsOneWidget;
import com.google.web.bindery.requestfactory.shared.Receiver;
import com.google.web.bindery.requestfactory.shared.ServerFailure;

/**
 * Activities are started and stopped by an ActivityManager associated with a container Widget.
 */
public class FlatsActivity extends AbstractActivity implements FlatsView.Presenter, FlatView.Presenter,BookingView.Presenter {

	
	private static final Logger log = Logger.getLogger(FlatsActivity.class.getName());
	

	private FlatsPlace place;
	private AppRequestFactory requestFactory;
	private PlaceController placeController;
	
	private FlatsView flatsView;
	
	private List<FacilityProxy> facilities;
	
	private AppFlatRequest appFlatRequest;
	
	private AppApplicationRequest appApplicationRequest;

	public FlatsActivity(FlatsPlace place,AppRequestFactory requestFactory,PlaceController placeController) {
	this.place=place;
	this.requestFactory=requestFactory;
	this.placeController=placeController;
		
	}

	@SuppressWarnings("deprecation")
	@Override
	public void start(AcceptsOneWidget containerWidget, EventBus eventBus) {
		
		log.info("Starting FlatsActivity");
		
		flatsView = FlatsViewImpl.instance(this);
		containerWidget.setWidget(flatsView.asWidget());
		
		appFlatRequest=requestFactory.appFlatRequest();
		
		if (place.getFlatId()!=null){
			

			flatsView.setFlatCount(1);	
			Long flatId=new Long((long)place.getFlatId());
			log.info("getVipFlat(Id):"+flatId);
			appFlatRequest.findVipFlat(flatId).with("fotos","facilities","metroStation").fire(new Receiver<FlatProxy>() {

				@Override
				public void onSuccess(FlatProxy flatProxy) {
					
					if (flatProxy!=null) flatsView.showFlat(flatProxy, true);
					else {
						flatsView.setFlatCount(0);
						flatsView.showFlatList();
						
					}
					
				}
			});
			
			
		}else{
		
			appFlatRequest.countVipFlats(place.getFacilityIds(),place.getMetroStation(),place.getRooms()).fire(new Receiver<Long>() {

				@Override
				public void onSuccess(Long flatCount) {
					
					flatsView.setFlatCount(flatCount.intValue());
					
					
				}
			});
			
		}
		
		
	}

	@Override
	public String mayStop() {
		return null;
	}

	/**
	 * @see FlatsView.Presenter#goTo(Place)
	 */
	public void goTo(Place place) {
		// TODO
	}

	@SuppressWarnings("deprecation")
	@Override
	public void onFlatRangeChange(final int rangeStart) {
		
		if (place.getFlatId()!=null) return;
		
		
		log.info("startLoading");
//		if (flatsView!=null) flatsView.startLoading();
		appFlatRequest=requestFactory.appFlatRequest();
		
		appFlatRequest.findVipFlats(rangeStart, 5,place.getFacilityIds(),place.getMetroStation(),place.getRooms()).with("fotos","facilities","metroStation").fire(new Receiver<List<FlatProxy>>() {

			@Override
			public void onSuccess(List<FlatProxy> flatProxies) {
				log.info("result obtained, size:"+flatProxies.size());
				flatsView.setRangeData(rangeStart, flatProxies);
				flatsView.showFlatList();
			}
		});
		
	}

//	@SuppressWarnings("deprecation")
//	private List<FacilityProxy> getFacilities(AppFlatRequest request) {
//		
//		if (facilities==null){
//			facilities=new ArrayList<FacilityProxy>();
//
//			List<String> ids=place.getFacilityIds();
//
//			if (ids!=null&&ids.size()>0){
//				for (String id:ids){
//					FacilityProxy facilityProxy=request.create(FacilityProxy.class);
//					facilityProxy.setId(id);
//					facilityProxy.setVersion(0);
//					facilities.add(facilityProxy);
//
//				}
//			}
//		}
//		return facilities;
//	}

	@Override
	public void backToMap() {
		flatsView.showMap();
		flatsView.removeSelection();
		
	}

	@Override
	public void backToFlatList() {
		flatsView.showFlatList();
	}
	
	@Override
	public void showBookingView(int flatId,boolean standAlone){
		flatsView.showBookingView(flatId,standAlone);
	}

	@Override
	public void sendButtonClicked() {
		AppApplicationRequest request=getAppApplicationRequest();
		final BookingView bookingView=flatsView.getBookingView();
		
		if (bookingView==null) return;
		
		ApplicationProxy applicationProxy=request.create(ApplicationProxy.class);
		applicationProxy.setEmail(bookingView.getEmail());
		applicationProxy.setInDate(bookingView.getInDate());
		applicationProxy.setName(bookingView.getName());
		applicationProxy.setNote(bookingView.getNote());
		applicationProxy.setObjectId(bookingView.getObjectId());
		applicationProxy.setOutDate(bookingView.getOutDate());
		applicationProxy.setPeopleNum(bookingView.getPeopleNum());
		applicationProxy.setTel(bookingView.getTel());
		
		request.commit().using(applicationProxy).fire(new Receiver<Void>() {
			@Override
			public void onSuccess(Void response) {
				
				bookingView.setCommittedView();
			}
			
			@Override
			public void onFailure(ServerFailure error) {
				Window.alert("Ошибка сервера. Попробуйте еще раз.");
				bookingView.setFormView();
			}
		});
		
		
	}
	
	private AppApplicationRequest getAppApplicationRequest(){
		
		appApplicationRequest=requestFactory.appApplicationRequest();
		
		return appApplicationRequest;
	}
	
	
}
